package edu.ynu.se.xiecheng.achitectureclass.project.service;

import edu.ynu.se.xiecheng.achitectureclass.project.po.dto.YsTokenRequest;
import edu.ynu.se.xiecheng.achitectureclass.project.po.dto.YsTokenResponse;
import edu.ynu.se.xiecheng.achitectureclass.project.po.entity.YsToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;


@Service
@Slf4j
public class YsTokenService {
    private static final String YS_TOKEN_URL = "http://42.193.14.241:7000/ysapi/subAccount/getToken";
    private static final String DEFAULT_ACCOUNT_ID = "1ca7f0ab24ba41b291346347ec30140e";

    @Autowired
    private RestTemplate restTemplate;

    public YsToken getToken() {
        try {
            YsTokenRequest request = new YsTokenRequest();
            request.setAccountId(DEFAULT_ACCOUNT_ID);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<YsTokenRequest> entity = new HttpEntity<>(request, headers);

            ResponseEntity<YsTokenResponse> response = restTemplate.postForEntity(
                    YS_TOKEN_URL,
                    entity,
                    YsTokenResponse.class
            );

            if (response.getStatusCode().is2xxSuccessful() &&
                    "200".equals(response.getBody().getCode())) {
                long expireTime = System.currentTimeMillis() + (7 * 24 * 60 * 60 * 1000);
                return new YsToken(
                        response.getBody().getData().getAccessToken(),
                        expireTime
                );
            } else {
                log.error("Failed to get YS token: {}", response.getBody().getMsg());
                throw new RuntimeException("Failed to get YS token");
            }
        } catch (Exception e) {
            log.error("Error getting YS token", e);
            throw new RuntimeException("Error getting YS token", e);
        }
    }
}